package com.tiennt.android.chinesechess.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

import com.tiennt.android.chinesechess.models.BanCo;
import com.tiennt.android.chinesechess.models.BitmapHolder;
import com.tiennt.android.chinesechess.models.Coord;
import com.tiennt.android.chinesechess.models.quanco.QuanCo;

public class GameView extends SurfaceView implements SurfaceHolder.Callback {

	// Drawing.
	private DrawingThread drawingThread;
	private Paint paint;
	private BitmapHolder bitmapHolder;
	private float mScaleFactor;

	// Debug purpose.
	private boolean DBG = true;
	private String TAG = "GameView";

	// Game.
	BanCo mBanCo;

	public GameView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.getHolder().addCallback(this);
		this.drawingThread = new DrawingThread(getHolder());
		this.setFocusable(true);

		paint = new Paint();
		bitmapHolder = new BitmapHolder(getContext());

		initialValue();
	}

	public void initialValue() {
		mBanCo = new BanCo(bitmapHolder);
	}

	public GameView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public void startDrawing() {
		drawingThread.setRunning(true);
		drawingThread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		setWillNotDraw(false);
		startDrawing();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		boolean retry = true;
		drawingThread.setRunning(false);
		while (retry) {
			try {
				drawingThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		canvas.save();

		float scaleX = getWidth() / 720f;
		float scaleY = getHeight() / 800f;
		mScaleFactor = Math.min(scaleX, scaleY);

		log("Scale: " + mScaleFactor);
		canvas.scale(mScaleFactor, mScaleFactor);
		drawOnCanvas(canvas);
		canvas.restore();

	}

	private void drawOnCanvas(Canvas canvas) {
		UIPainter.drawGameBackground(canvas, paint);
		// UIPainter.drawBanCoUpStart(canvas, paint,
		// bitmapHolder.getBitmap(BitmapHolder.TenQuanCo.UP_DO));
		// UIPainter.drawBanCoThuongStart(canvas, paint, bitmapHolder);
		// UIPainter.drawHint(canvas, paint, 5, 5);
		mBanCo.drawBanCo(canvas, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {

		final int action = ev.getAction();
		switch (action & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN: {
			final float x = ev.getX();
			final float y = ev.getY();

			Coord c = mBanCo.translateXyToCoord(x, y, mScaleFactor);
			if (c != null && (c.mCot > 8 || c.mHang > 9)) {
				break;
			}

			if (mBanCo.mSelectedQc == null) {
				if (c != null) {
					mBanCo.mSelectedQc = mBanCo.mOCo[c.mHang][c.mCot].mQuanCo;
					if (mBanCo.mSelectedQc != null) {
						mBanCo.mSelectedQc.toggleTrangThai();
					}

				}
			} else {
				// Da co quan co duoc chon.
				if (c != null) {
					// Vi tri co the di co.
					if (mBanCo.mSelectedQc.mHang == c.mHang
							&& mBanCo.mSelectedQc.mCot == c.mCot) {
						mBanCo.mSelectedQc.toggleTrangThai();
						mBanCo.mSelectedQc = null;
					} else {
						int status = mBanCo.mSelectedQc.isValidMove(c.mHang,
								c.mCot);
						if (status == QuanCo.cNOTVALIDMOVE_BICHIEU) {
							// Bi chieu.
							Toast.makeText(getContext(), "Tuong minh bi chieu",
									Toast.LENGTH_SHORT).show();
							break;
						} else if (status == QuanCo.cNOTVALIDMOVE_CHONGTUONG) {
							// Chong tuong
							Toast.makeText(getContext(), "Chong tuong",
									Toast.LENGTH_SHORT).show();
							break;
						} else if (status == QuanCo.cVALIDMOVE) {
							mBanCo.mSelectedQc.moveTo(c.mHang, c.mCot);
							mBanCo.mSelectedQc = null;
						} else {
							mBanCo.mSelectedQc.toggleTrangThai();
							mBanCo.mSelectedQc = mBanCo.mOCo[c.mHang][c.mCot].mQuanCo;
							if (mBanCo.mSelectedQc != null) {
								mBanCo.mSelectedQc.toggleTrangThai();
							}
						}
					}
				} else {
					mBanCo.mSelectedQc.toggleTrangThai();
					mBanCo.mSelectedQc = null;
				}
			}

			log("--------------------------------------------------------------");
			invalidate();
			break;
		}

		case MotionEvent.ACTION_MOVE: {
			break;
		}

		case MotionEvent.ACTION_UP: {
			break;
		}

		case MotionEvent.ACTION_CANCEL: {
			break;
		}

		case MotionEvent.ACTION_POINTER_UP: {
			break;
		}
		}

		return true;
	}

	public void log(final String message) {
		if (DBG) {
			Log.d(TAG, message);
		}
	}

	private class DrawingThread extends Thread {

		private SurfaceHolder surfaceHolder;
		private boolean isRunning = false;

		public DrawingThread(SurfaceHolder sh) {
			surfaceHolder = sh;
		}

		public void setRunning(boolean isRun) {
			this.isRunning = isRun;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			Canvas canvas;

			while (isRunning) {
				canvas = null;
				try {
					canvas = surfaceHolder.lockCanvas();
					GameView.this.postInvalidate();
				} finally {
					if (canvas != null) {
						surfaceHolder.unlockCanvasAndPost(canvas);
					}
				}
				isRunning = false;

			}
		}

	}

}
